package com.duang.framework.config;

import java.util.ArrayList;
import java.util.List;

import com.duang.framework.cache.CacheConfiguration;
import com.duang.framework.cache.ManagerConfiguration;
import com.duang.framework.cache.plugin.ehcache.EhcacheProviderFactory;
import com.duang.framework.dao.Plugin;
import com.duang.framework.dao.plugin.C3p0Plugin;

public abstract class ApplicationConfigurationPluginSupport extends
		ApplicationConfigurationImpl implements ConfigurablePlugin {

	private List<Plugin> pluginList = new ArrayList<Plugin>();

	protected abstract void configurePluginContext();

	void stopPlugins() {
		for (Plugin plugin : pluginList) {
			plugin.stop();
		}
	}

	void startPlugins() {
		for (Plugin plugin : pluginList) {
			plugin.start();
		}
	}

	@Override
	public void useDatabaseConnectionPool(DatabaseConnectionPoolType type,
			String jdbcUrl, String username, String password, String driverClass) {
		if (type != null)
			this.databaseConnectionPoolType = type;
		if (type == DatabaseConnectionPoolType.C3P0) {
			if (isDedug())
				System.out.println("use c3p0 connection pool");
			C3p0Plugin c3p0 = new C3p0Plugin(jdbcUrl, username, password,
					driverClass);
			this.dataSourceProvider = c3p0;
			System.out.println("datasource---->"
					+ this.dataSourceProvider.getDataSource());
			pluginList.add(c3p0);
		}
	}

	@Override
	public final void useCacheProvider(CacheProviderType type,
			ManagerConfiguration configuration) {
		if (type != null)
			this.cacheProviderType = type;
		if (type == CacheProviderType.EHCACHE) {
			cacheProviderFactory = new EhcacheProviderFactory();
			cacheProvider = cacheProviderFactory
					.createCacheProvider(configuration);
			if (cacheProvider
					.getCache(com.duang.framework.cache.Constants.AOP_METHOD_INVOKE_CACHE_NAME) == null) {
				CacheConfiguration cacheConfiguration = new CacheConfiguration();
				configuration.setAopMethodInvokeCache(cacheConfiguration);
			}
			pluginList.add(cacheProvider);
		}
	}

	final void configurePlugins() {
		configurePluginContext();
		startPlugins();
	}
}
